package com.wjy.common.log.time;

import com.wjy.common.annotation.RunTime;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author ybxxszl
 * @desc 运行时间日志
 * @date 2019/4/16
 */
@Component
@Log4j2
@Aspect
public class RunTimeLog {

    // @Pointcut(value = "within(@org.springframework.stereotype.Controller *)")
    // public void runTimeLogController() {
    //
    // }
    //
    // @Pointcut(value = "within(@org.springframework.web.bind.annotation.RestController *)")
    // public void runTimeLogRestController() {
    //
    // }
    //
    // @Pointcut(value = "runTimeLogController()||runTimeLogRestController()")
    // public void runTimeLog() {
    //
    // }
    //
    // @Around(value = "runTimeLog()")
    // public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    // Signature signature = proceedingJoinPoint.getSignature();
    // MethodSignature methodSignature = (MethodSignature)signature;
    // Method method = methodSignature.getMethod();
    // RunTime runTime = AnnotationUtils.getAnnotation(method, RunTime.class);
    //
    // long startTime = System.currentTimeMillis();
    // Object object = proceedingJoinPoint.proceed();
    // long endTime = System.currentTimeMillis();
    //
    // if (runTime != null && !runTime.ignore()) {
    // log.info(runTime.value() + "执行时间：" + (endTime - startTime) + "ms");
    // }
    //
    // return object;
    // }

    @Pointcut(value = "execution(@com.wjy.common.annotation.RunTime * *(..))")
    public void runTimeLog() {

    }

    @Around(value = "runTimeLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Signature signature = proceedingJoinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        RunTime runTime = AnnotationUtils.getAnnotation(method, RunTime.class);

        long startTime = System.currentTimeMillis();
        Object object = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();

        if (runTime != null && !runTime.ignore()) {
            log.info(runTime.value() + "执行时间：" + (endTime - startTime) + "ms");
        }

        return object;
    }

}
